﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Configuration;
using JLL.China.Infrastructure.Services;
using JLL.China.Model;
using JLL.China.Web.Areas.Listings.Models;
using JLL.China.Application;
using JLL.China.Application.Services.Authentication;
using JLL.China.Web.Controllers;
using JLL.China.Web.Libraries;

namespace JLL.China.Web.Areas.Listings.Controllers
{
    public class ProjectDirectoryController : BaseController
    {
        
        protected int defaultPageSize = Int32.Parse(WebConfigurationManager.AppSettings["page_size_default"]);
       
        public ProjectDirectoryController()
        {
            ViewData["AjaxPage"] = "CountProjectDirectory/";
            ViewData["Module"] = "ProjectDirectory";
        }
        
        // Search
        public ActionResult Search(int? page)
        {


            if (Session["page_size_default"] != null)
            {
                ViewData["per-page"] = Session["page_size_default"].ToString();
                defaultPageSize = Int32.Parse(Session["page_size_default"].ToString());
            }
            else
            {
                ViewData["per-page"] = defaultPageSize;
            }
            int currentPageIndex = page.HasValue ? page.Value : 1;
            //Strore Session

            Session["pageindex"] = currentPageIndex;
            ViewData["ListStatus"] = 0;

            // Get Query Search
            var property = new JLL.China.Web.Areas.Listings.Models.ProjectDirectoryModel();

            //
            if (Request.QueryString["SearchAction"] != null)
            {
                if (Request.QueryString["City"]!=null)
                {
                    if (Request.QueryString["City"].ToString() != "")
                    {
                        property._listingCriteria.CityID = Int32.Parse(Request.QueryString["City"]);
                        ViewData["CityID"] = Request.QueryString["City"];
                    }
                }
                
                if(Request.QueryString["Location"]!=null){
                    if (Request.QueryString["Location"].ToString() != "")
                    {
                        var LocationID = Int32.Parse(Request.QueryString["Location"]);
                        property._listingCriteria.LocationID = LocationID;
                        ViewData["LocationID"] = LocationID;
                    }
                }
                if (Request.QueryString["Subarea"]!=null)
                {
                     if (Request.QueryString["Subarea"].ToString() != "")
                    {
                        var SubareaID = Int32.Parse(Request.QueryString["Subarea"]);
                        property._listingCriteria.SubAreaID = SubareaID;
                        ViewData["SubareaID"] = SubareaID;
                    }
                }
               
                //Country
                if (Request.QueryString["Country"] != null)
                {
                    if (Request.QueryString["Country"].ToString() != "")
                    {
                        var Country = Int32.Parse(Request.QueryString["Country"]);
                        property._listingCriteria.CountryID = Country;
                        ViewData["Country"] = Country;
                    }
                }
                 //Country
                if (Request.QueryString["CityInt"] != null)
                {
                    if (Request.QueryString["CityInt"].ToString() != "")
                    {
                        var CityInt = (Request.QueryString["CityInt"]);
                        property._listingCriteria.CityName = CityInt;
                        ViewData["CityInt"] = CityInt;
                    }
                }
               
               

                //PropertyType

                //

                if (Request.QueryString["PropertyType"].ToString() != "")
                {
                    var PropertyType = Int32.Parse(Request.QueryString["PropertyType"]);
                    property._listingCriteria.PropertyTypeID = PropertyType;
                    ViewData["PropertyType"] = PropertyType;
                }
                //Property Status
                int? IdStatus = null;
                if (Request.QueryString["Status"].ToString() != "")
                {
                    IdStatus = Int32.Parse(Request.QueryString["Status"]);
                    property._listingCriteria.Status = IdStatus;
                    ViewData["Status"] = IdStatus;
                }
                //Property Classification
                if (Request.QueryString["PropertyClss"].ToString() != "")
                {
                    var PropertyClss = Request.QueryString["PropertyClss"];
                    property._listingCriteria.PropertyClassification = PropertyClss;
                    ViewData["PropertyClss"] = PropertyClss;
                }
                //Property Tenure
                if (Request.QueryString["Tenure"].ToString() != "")
                {
                    var Tenure = Request.QueryString["Tenure"];
                    property._listingCriteria.Tenure = Tenure;
                    ViewData["Tenure"] = Tenure;
                }
                //Property Keyword
                if (Request.QueryString["Keyword"].ToString() != "")
                {
                    var Keyword = Request.QueryString["Keyword"];
                    property._listingCriteria.Keyword = Keyword;
                    ViewData["Keyword"] = Keyword;
                }
                //
                string ControllerName =this.ControllerContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
                if (ControllerName == "ProjectDirectoryLocal")
                {
                    var model = property.GetLocalByStatus(IdStatus).ToPagedList(currentPageIndex, defaultPageSize);
                    ViewData["TotalRecord"] = "Found " + property.CountListing + " records";

                    return View("../ProjectDirectory/Search", model);
                }

                else
                {
                    var model = property.GetInternationalByStatus(IdStatus).ToPagedList(currentPageIndex, defaultPageSize);
                    ViewData["TotalRecord"] = "Found " + property.CountListing + " records";

                    return View("../ProjectDirectory/Search", model);
                }

               
            }
            else
            {
                ViewData["TotalRecord"] = "Results";
                var model = property.GetLocalByStatus(8).ToPagedList(currentPageIndex, defaultPageSize);
                return View("../ProjectDirectory/Search", model);
            }


            //
            //

        }
       //
        
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangeNumOfRow(FormCollection f)
        {
            Session["messageType"] = "Success";
            Session["page_size_default"] = f["display_show_page"].ToString();
            Session["message"] = "Changed number of row";
            return RedirectToAction("Index");
        }
        public ActionResult Step1(int? id, string Language)
        {
            if (id != null)
            { //for edit
                var model = ProjectDirectoryService.FindById((int)id);
                if (model!=null)
                {
                    ViewData["StatusID"] = model.StatusFID;
                    ViewData["ListingID"] = id;
                    return View("../ProjectDirectory/Step1", model);
                }
                return RedirectToAction("Index");
                
            }
            else
            {
                return View("../ProjectDirectory/Step1");
            }

        }
        [HttpPost, ValidateInput(false)]
        public ActionResult Step1(FormCollection form)
        {
            try
            {
                // Two the kind
                //1.Local
                //Set default for internal
                decimal CityFID = 0;
                decimal LocaltionFID = 0;
                decimal SubAreaFID = 0;
                string CityInternational = "";
                if (form["CityInt"] != null)
                {
                    CityInternational = form["CityInt"].ToString();
                }
                string IsLocal = form["IsLocal"].ToString().Trim();
                int? CountryId = null;
                if (IsLocal == "LOCAL")
                {
                    CityFID = decimal.Parse(form["City"].ToString());
                    LocaltionFID = decimal.Parse(form["Location"].ToString());
                    if (form["Subarea"] != null)
                    {
                        if (form["Subarea"].ToString() != "")
                        {
                            SubAreaFID = decimal.Parse(form["Subarea"].ToString());
                        }

                    }

                    //China
                    CountryId = JLL.China.Web.Libraries.HelperUtility.GetIdCountry();
                }
                else
                {
                    CountryId = Int32.Parse(form["Country"].ToString().Trim());
                }

                //Login User
                var loginAcc = this.Session[Constants.Session_User] as Model.Admin;
                int ListingID = 0;
                string _strUpdateBy = null;
                if (form["ListingID"].ToString() != "")
                {
                    ListingID = int.Parse(form["ListingID"].ToString().Trim());
                    _strUpdateBy = loginAcc.UserName;
                }
                string ProjectName = form["ProjectName"].ToString().Trim();
                string ProjectNameLocal = form["ProjectNameLocal"].ToString().Trim();
                decimal? proID = null;
                //INSERT & UDPATE
                if (form["ProjectNameFID"].ToString() != "")
                {
                    proID = decimal.Parse(form["ProjectNameFID"].ToString());
                }

                int ProjectNameFID = ProjectNameService.Add(proID, ProjectName, ProjectNameLocal,IsLocal);
                //STREETNAME
                decimal? streetID = null;
                //INSERT & UDPATE
                //Store
                int StreetNameFID = Int32.Parse(form["StreetName"].ToString());
                //
                decimal PropertyTypeFID = decimal.Parse(form["PropertyType"].ToString().Trim());
                string PropertyClsssm = form["PropertyClsssm"].ToString();
                string Tenure = form["Tenure"].ToString().Trim();

                string Description = (form["Description"].ToString().Trim());
                string DescriptionLocal = (form["DescriptionLocal"].ToString().Trim());
                string _strHouseNumber = form["HouseNumber"].ToString().Trim();
                string ListingSource = "Admin";
                //


                var listing = new Model.ProjectDirectory
                {
                    ID = ListingID,
                    ListingSource = ListingSource,
                    ProjectNameFID = ProjectNameFID,
                    StreetNameFID = StreetNameFID,
                    PropertyTypeFID = PropertyTypeFID,
                    PropertyClsssm = PropertyClsssm,
                    CityFID = CityFID,
                    LocaltionFID = LocaltionFID,
                    SubAreaFID = SubAreaFID,
                    Tenure = Tenure,
                    Description = Description,
                    DescriptionLocal = DescriptionLocal,
                    CountryFID = (int)CountryId,
                    City = CityInternational,
                    CreateBy = loginAcc.UserName,
                    UpdateBy = _strUpdateBy,
                    HouseNumber = _strHouseNumber,
                };
                //
                int ListignID = ProjectDirectoryService.Store(listing);
                Session["messageType"] = "Success";
                Session["message"] = "Updated successfully.";
                return RedirectToAction("Step2/" + ListignID.ToString());
            }
            catch
            {
              
                this.Session.Remove(Constants.Session_Role);
                this.Session.Remove(Constants.Session_User);

                return RedirectToAction("Index");
            }
           

        }
        public ActionResult Step2(int? id)
        {
            var model = new ProjectDirectoryDetailModel();
            if (id != null)
            { //for edit
               
                model.projectdir = ProjectDirectoryService.GetProjectDirDetail((int)id, 1);
                model.localprojectdir = ProjectDirectoryService.GetProjectDirDetail((int)id, 2);
                ViewData["ListingID"] = id.Value.ToString();

                ViewData["StatusID"] = "";
                return View("../ProjectDirectory/Step2", model);
            }
           else
            {
                return RedirectToAction("Index");
            }
            
           
        }
        //
        public ActionResult Step4(int? id)
        {

            if (id != null)
            { //for edit
                var model = ProjectDirectoryService.FindById((int)id);
                ViewData["ListingID"] = id;
                ViewData["Latitude"] = model.Latitude;
                ViewData["Longitude"] = model.Longitude;
                ViewData["StatusID"] = model.StatusFID;
                return View("../ProjectDirectory/Step4");
            }
            return RedirectToAction("Index");
            

        }
        //
        [HttpPost]
        public ActionResult Step4(FormCollection form)
        {
            int ListingID = 0;
            if (form["ListingID"].ToString() != "")
            {
                ListingID = Int32.Parse(form["ListingID"].ToString());
                string lat = form["lat"].ToString().Trim();
                string lng = form["lng"].ToString().Trim();
                var listing = new Model.ProjectDirectory
                {
                    ID = ListingID,
                    Longitude = lng,
                    Latitude = lat
                };
                ProjectDirectoryService.Update(listing);
                ProjectDirectoryService.Save();

                Session["messageType"] = "Success";
                Session["message"] = "Updated successfully.";
            }
            return RedirectToAction("Step5/" + ListingID);
        }
        //
        public ActionResult Step3(int? id)
        {
          
            if (id != null)
            {
                var model = ProjectDirectoryService.FindById((int)id);
                ViewData["ListingID"] = id;
                ViewData["StatusID"] = model.StatusFID;
                return View("../ProjectDirectory/Step3",model);
            }
            else
            {
                return RedirectToAction("Index");
            }
            
         
        }
        //
        [HttpPost]
        public ActionResult Step3(int id,IEnumerable<int> Facilities, IEnumerable<int> Features)
        {
            //
            string _Facilities = "0";
            if (Facilities != null)
            {
                foreach (var key in Facilities)
                {
                    _Facilities += "," + key.ToString();
                }
                _Facilities = _Facilities.Replace("0,", "");
            }
            else
            {
                _Facilities = _Facilities.Replace("0", "");
            }
            //
            string _Features = "0";
            if (Features != null)
            {
                foreach (var key in Features)
                {
                    _Features += "," + key.ToString();
                }
                _Features = _Features.Replace("0,", "");
            }
            else
            {
                _Features = _Features.Replace("0", "");
            }
            //
            ProjectDirectoryService.UpdateStep3(id, _Features, _Facilities);
            Session["messageType"] = "Success";
            Session["message"] = "Updated successfully.";
           
            return RedirectToAction("Step4/" + id.ToString());
           
        }
        //
        public ActionResult Step5(int? id)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            if (id != null)
            { //for edit
                ViewData["ListingID"] = id;
                ViewData["ImageList"] = ProjectDirectoryMediaService.GetListImage((int)id);
                ViewData["TotalPhoto"] = ProjectDirectoryMediaService.getCountItem();
                var model = ProjectDirectoryService.FindById((int)id);
                if (model != null)
                {
                    ViewData["StatusID"] = model.StatusFID;
                    return View("../ProjectDirectory/Step5");
                }
               
                
                    return RedirectToAction("Index");
               
              
            }
            else
            {
                return RedirectToAction("Index");
            }
        }
        //
        //
        public ActionResult Step6(decimal? id, decimal? prjDirFloorPlan_ID)
        {
           
            if (id != null)
            { //for edit
                ViewData["ListingID"] = id;
                Session["ListingID"] = id;
                var m = ProjectDirectoryService.FindById((int)id);
                ViewData["StatusID"] = m.StatusFID;
                var l = PrjDirFlrPlanService.FindByListingID_Language(id, 1);
                ViewData["ProjectFloor"] = l;
                var prj = PrjDirFlrPlanService.FindByID_Language(prjDirFloorPlan_ID, 1);
                var prj1 = PrjDirFlrPlanService.FindByID_Language(prjDirFloorPlan_ID, 2);
                var model = new Models.PrjDirFlrPlanModel();
                model.PrjDirFlrPlan = prj;
                model.PrjDirFlrPlan_Local = prj1;
                return View("../ProjectDirectory/Step6",model);
            }
            else
            {
                return View("../ProjectDirectory/Step5");
            }
        }
        
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Step6(Models.PrjDirFlrPlanModel model,HttpPostedFileBase floorImg)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            if (floorImg != null)
            {
                 BinaryReader b = new BinaryReader(floorImg.InputStream);
                 byte[] binData = b.ReadBytes(floorImg.ContentLength);
                  Image orig = HelperUtility.byteArrayToImage(binData);
                  var imgthumb = HelperUtility.imageToByteArray(HelperUtility.GetThumbImage(orig,650,orig.Width,orig.Height));
                  model.PrjDirFlrPlan.FloorPlanImg = imgthumb;
            }
            model.PrjDirFlrPlan.ListingFID = decimal.Parse(Session["ListingID"].ToString());
            if (model.PrjDirFlrPlan.ProjectDirFloorPlan_ID == null) //insert
            {


               
                PrjDirFlrPlanService.Create(model.PrjDirFlrPlan, model.PrjDirFlrPlan_Local);
                //                Session["message"] = "Records updated successfully.";
                //                Session["messageType"] = "Success";
                // return View("../Content/Create");
            }
            else //for update
            {


                PrjDirFlrPlanService.Update(model.PrjDirFlrPlan, model.PrjDirFlrPlan_Local);
                //                Session["message"] = "Records updated successfully.";
                //                Session["messageType"] = "Success";
            }
            ShowMessage("Records updated successfully.", "Success");

            return RedirectToAction("Step6/" + Session["ListingID"].ToString());
        }

        public ActionResult DeleteStep6(decimal id)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            decimal res = PrjDirFlrPlanService.Deleted(id);
            if(res != -1)
                ShowMessage("Records updated successfully.", "Success");
            else
                ShowMessage("Records updated unsuccessfully.", "Error");

            return RedirectToAction("Step6/" + Session["ListingID"].ToString());
        }
        /*----------------------------------------------start step 6-------------------------------------------------------*/
        public ActionResult ShowFloorImg(decimal id)
        {

           var imageData = PrjDirFlrPlanService.FindByID_Language(id, 1).FloorPlanImg;
            if (imageData == null)
            {
                //return new FilePathResult("~/Content/Images/NoPhoto.png", "image/png");
                string filePath = Server.MapPath("~/Content/images/no_img_default.png");
                string fileName = Path.GetFileName(filePath);
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                var eximg = br.ReadBytes((Int32)fs.Length);
                return File(eximg, "image/jpg");
            }
            else
            {

                return new FileContentResult(imageData.ToArray(), "image/jpeg");
            }
            //return File( imageData, "image/jpg" );
        }
        void ShowMessage(string msg, string type)
        {
            Session["message"] = msg;
            Session["messageType"] = type;
        }
        public bool checkUserLogin()
        {
            var loginAcc = this.Session[Constants.Session_User] as Model.Admin;
            if (loginAcc == null)
            {
                return false;
            }
            return true;
        }
        /*-------------------------------------------------------end step 6-------------------------------------------------------*/
        //
        public ActionResult Step7(int? id)
        {
            if (id != null)
            { //for edit
                ViewData["ListingID"] = id;
                ViewData["StatusID"] = "";
                return View("../ProjectDirectory/Step7");
            }
            else
            {
                ViewData["StatusID"] = "";
                return View("../ProjectDirectory/Step7");
            }
        }
        //
        [HttpPost, ValidateInput(false)]
        public ActionResult Step2(ProjectDirectoryDetailModel prodetail)
        {
            var item = prodetail.projectdir;
            item.LanguageID = 1;
          
            ProjectDirectoryService.UpdateStep2(item);

            var localitem = prodetail.localprojectdir;
            localitem.LanguageID = 2;
            localitem.SiteArea = item.SiteArea;
            ProjectDirectoryService.UpdateStep2(localitem);

            Session["messageType"] = "Success";
            Session["message"] = "Updated successfully.";

           
             return RedirectToAction("Step3/" + item.ListingFID.ToString());
          
        }
       
        public ActionResult Active(int id,int? status)
        {
            try
            {

                ProjectDirectoryService.ChangeStatus(id.ToString(), 1);
                Session["messageType"] = "Success";
                Session["message"] = "Status updated successfully.";
                if (Session["pageindex"] != null)
                {
                    return RedirectToAction("Index/" + status.Value.ToString() + "?page=" + Session["pageindex"].ToString());
                }
                else
                {
                    return RedirectToAction("Index/" + status.Value.ToString() );
                }

            }
            catch
            {
                return RedirectToAction("Index");
            }
        }
        public ActionResult Draft(int id, int? status)
        {
            try
            {

                ProjectDirectoryService.ChangeStatus(id.ToString(), 2);
                Session["messageType"] = "Success";
                Session["message"] = "Status updated successfully.";

                return RedirectToAction("Index/" + status.Value.ToString()+ "?page=" + Session["pageindex"].ToString());
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }
        public ActionResult Delete(int id, int? status)
        {
            try
            {

                ProjectDirectoryService.ChangeStatus(id.ToString(), 3);
                Session["messageType"] = "Success";
                Session["message"] = "Status updated successfully.";
                return RedirectToAction("Index/" + status.Value.ToString() + "?page=" + Session["pageindex"].ToString());
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }
        //
        // POST//BulkProcess
        //
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult BulkProcess(string id, IEnumerable<int> selected)
        {

            try
            {
                string arr_id = "0";
                foreach (var key in selected)
                {
                    arr_id += "," + key.ToString();
                }
                //
                if (id == "Active")
                {

                    ProjectDirectoryService.ChangeStatus(arr_id, 1);
                    Session["messageType"] = "Success";
                    Session["message"] = "Records updated successfully.";
                    return RedirectToAction("Index/1?page=" + Session["pageindex"].ToString());
                }
                //
                if (id == "Draft")
                {
                    ProjectDirectoryService.ChangeStatus(arr_id, 2);
                    Session["messageType"] = "Success";
                    Session["message"] = "Records updated successfully.";
                    return RedirectToAction("Index/2?page=" + Session["pageindex"].ToString());
                }
                //
                if (id == "Delete")
                {
                    ProjectDirectoryService.ChangeStatus(arr_id, 3);
                    Session["messageType"] = "Success";
                    Session["message"] = "Records updated successfully.";
                    return RedirectToAction("Index/3?page=" + Session["pageindex"].ToString());
                }

                return RedirectToAction("Index");
            }
            catch
            {

                return RedirectToAction("Index");
            }
        }

        #region "Image Media"
        public ActionResult RemoveImg(int id)
        {
            try
            {
                var media = ProjectDirectoryMediaService.GetProjectDirectoryMediaById(id);
               if(media != null){
                   ProjectDirectoryMediaService.Delete(media);
                   ProjectDirectoryMediaService.Save();
                   Session["messageType"] = "Success";
                   Session["message"] = "Deleted successfully.";
                   
                   return RedirectToAction("/Step5/" + media.ListingsFID.ToString());
               }
               return View("../ProjectDirectory/Step1/");
            }
            catch
            {
                return View("../ProjectDirectory/Step1/");
            }
        }
        public ActionResult ChangeStatusImg(int id)
        {
            try
            {
                var media = ProjectDirectoryMediaService.GetProjectDirectoryMediaById(id);
                if (media.IsActive == true)
                {
                    media.IsActive = false;
                }
                else
                {
                    media.IsActive = true;
                }
                ProjectDirectoryMediaService.Update(media);
                ProjectDirectoryMediaService.Save();
                Session["messageType"] = "Success";
                Session["message"] = "Updated successfully.";
                return RedirectToAction("/Step5/" + media.ListingsFID.ToString());
            }
            catch
            {
                return View("../ProjectDirectory/Step1/");
            }
        }
        public ActionResult SetDefaultImg(int id)
        {
            try
            {
                var media = ProjectDirectoryMediaService.GetProjectDirectoryMediaById(id);
                if (media.IsDefault == true)
                {
                    media.IsDefault = false;
                }
                else
                {
                    media.IsDefault = true;
                }
                ProjectDirectoryMediaService.Update(media);
                ProjectDirectoryMediaService.Save();
                Session["messageType"] = "Success";
                Session["message"] = "Updated successfully.";
                return RedirectToAction("/Step5/" + media.ListingsFID.ToString());
            }
            catch
            {
                return View("../ProjectDirectory/Step1/");
            }
        }
        #endregion


        public string SaveOrder(string id)
        {

            string[] arrData = id.Split(',');
            int countnum = arrData.Length;
            for (int i = 0; i < countnum; i++)
            {
                // UpdateOrder(arrData[i],i+1,1);
                // UpdateOrder(arrData[i], i + 1, 2);

            }
            for (int i = 0; i < arrData.Length; i++)
            {
                ProjectDirectoryMediaService.UpdateOrder(decimal.Parse(arrData[i]), i + 1);
            }
            return "OK";
        }
    }
}
